<?php
/**
 * User
 * 
 * @author ShuangYa
 * @package Example
 * @category Service
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2019 ShuangYa
 */
namespace App\Service;

use App\Model\Command as ModelCommand;
use App\Model\Device;
use App\Model\User as UserModel;
use Psr\SimpleCache\CacheInterface;

class Command {
	const CACHE_TIME = 3600;
	const CACHE_KEY = 'user_';
	// 等待
	const STATUS_PENDING = 'pending';
	// 运行中
	const STATUS_EXECUTE = 'execute';
	// 运行超时
	const STATUS_TIMEOUT = 'timeout';
	// 运行成功
	const STATUS_SUCCESS = 'success';
	// 运行失败
	const STATUS_ERROR = 'error';

	private $command;
	private $device;

	public function __construct(ModelCommand $command, Device $device) {
		$this->command = $command;
		$this->device = $device;
	}

	public function getModel() {
		return $this->command;
	}

	/**
	 * 检查命令状态，如果需要修改则自动修改
	 */
	private function checkCommand(&$command) {
		// 如果是3分钟以上还没有结果的，则置为超时
		if (($command['status'] === self::STATUS_PENDING || $command['status'] === self::STATUS_EXECUTE) && strtotime($command['create_time']) - time() > 180) {
			$command['status'] = self::STATUS_TIMEOUT;
			$this->command->set([
				'status' => self::STATUS_TIMEOUT
			], $command['id']);
		}
		return $command;
	}

	public function get($id) {
		$result = $this->command->get($id);
		return $this->checkCommand($result);
	}

	public function set($set, $id) {
		return $this->command->set($set, $id);
	}

	public function list($filter) {
		$result = $this->command->list($filter);
		foreach ($result as &$item) {
			$this->checkCommand($item);
		}
		// 过滤状态
		if (is_array($filter) && isset($filter['status'])) {
			$result = array_filter($result, function($item) use ($filter) {
				return $item['status'] === $filter['status'];
			});
		}
		return $result;
	}

	public function add($data) {
		return $this->command->add(array_merge($data, [
			'status' => self::STATUS_PENDING,
			'create_time' => date('Y-m-d H:i:s'),
			'msg' => ''
		]));
	}
}